// 此页代码处理客服消息

var path = require('path')

var Promise = require('bluebird')
var request = Promise.promisify(require('request'))

// 上传临时素材的方法
var uploadTempMedia = require('./uploadmedia')
var tempMediaPath = {
    addServr:path.join(__dirname, './tempmedia/mpServr_AddServr.jpg'),
    addPrdGroup:path.join(__dirname, './tempmedia/mpServr_AddPrdGroup.jpg')
}

// 微信接口地址公共部分
var prefix = 'https://api.weixin.qq.com/cgi-bin/'
// 微信接口地址非公共部分。
var api = {
    consult: prefix + 'message/custom/send?access_token=',
    uploadTempMedia: prefix + 'media/upload?access_token='
}

exports.service = function(message, token, res) {
    var url = api.consult + token.access_token
    var accToken = token.access_token
    console.log(message)
    if (message.MsgType === 'miniprogrampage') {
        var mplink = `<a href="https://mp.weixin.qq.com/s/LjqFBIBAAeDNxqbvgaBzmw">戳这里</a>`
        var h5link = `<a href="https://www.baidu.com">戳这里</a>`
        const formtext = {
            "touser": message.FromUserName,
            "msgtype": "text",
            "text": {
                "content": `嗯、又是一个读表铲屎官。\n欢迎使用敲懂成分表的选粮神器!\n猫粮助手为所有「成分党」铲屎官服务!\n\n回复「1」添加人工小助理\n回复「2」加入产品讨论群`
            }
        }


        request({ method: 'POST', url: url, body: formtext, json: true }).then((response) => {
            console.log(response)
        })
    } else if (message.MsgType === 'text') {
        if (message.Content === '1') {

            
            uploadTempMedia.uploadTempMedia(api, accToken, 'image', tempMediaPath.addServr).then((result) => {
                //console.log(result.media_id)
                
                const formimage = {
                    "touser": message.FromUserName,
                    "msgtype": "image",
                    "image": {
                        "media_id": result.media_id
                    }
                }

                request({ method: 'POST', url: url, body: formimage, json: true }).then((response) => {
                    //console.log(response)
                })

            })

        } else if (message.Content === '2') {
            uploadTempMedia.uploadTempMedia(api, accToken, 'image', tempMediaPath.addPrdGroup).then((result) => {
                //console.log(result.media_id)
                
                const formimage = {
                    "touser": message.FromUserName,
                    "msgtype": "image",
                    "image": {
                        "media_id": result.media_id
                    }
                }

                request({ method: 'POST', url: url, body: formimage, json: true }).then((response) => {
                    //console.log(response)
                })

            })
        }
    }
    res.send('')

}